function split(s, delim)
    if type(delim) ~= "string" or string.len(delim) <= 0 then
        return
    end
    local start = 1
    local t = {}
    while true do
    local pos = string.find (s, delim, start, true) -- plain find
        if not pos then
          break
        end
        table.insert (t, string.sub (s, start, pos - 1))
        start = pos + string.len (delim)
    end
    table.insert (t, string.sub (s, start))

    return t
end

function split_num(str, delimiter)
	if str==nil or str=='' or delimiter==nil then
		return nil
	end
	
    local result = {}
    for match in (str..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, tonumber(match))
    end
    return result
end

function rle_to_array(rle_exp) 
    result={}
    splt = split_num(rle_exp, ",")
    start = splt[1]
    pos = -1

    for i=2,#splt do 
        print(i)
        for rl=1,splt[i] do
            if (start==0 and i%2==1) or (start==1 and i%2==0) then 
                print("xx")
                table.insert(result, pos + rl)
            end
        end
        pos = pos + splt[i]
    end
    return result
end

function find_in_x(x, to_find)
    subs = split(x, "\t")  -- fixme xxx
    for k,v in pairs(subs) do 
        if v:find(to_find..":") then
            xxlen=string.len(to_find)+2
            return v:sub(xxlen)
        end
    end
    return nil
end

-----------------------------------------
local redis = require "resty.redis"
local cjson = require "cjson"

local red = redis:new()

red:set_timeout(1000) -- 1 sec
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

local args = ngx.req.get_uri_args()

uid = args.key
suid = uid:sub(-12)  --截取后12位
m_key = suid:sub(1,4)  --截取最后12位
s_key = suid:sub(5, 12) 


local res, err = red:get(m_key) --res tid表达式/rle表达式

tid=""
if not res then --redis无响应
    tid = ""
elseif res == ngx.null then --响应空
    tid = ""
else --响应的是subkey:RLE \t
    my_exp = find_in_x(res, s_key) --从里面找到sub key对应的表达式
    if not my_exp then
        tid = ""
    elseif not my_exp:find(",") then --响应的是单个tid
        local res1, err1 = red:get(my_exp)
        tid = res1
    else
        rle_ids = rle_to_array(my_exp)
        real_ids = {}
        for rle_k,rle_v in pairs(rle_ids) do 
            local res2, err2 = red:get(rle_v)
            table.insert(real_ids, res2)
        end
        tid = table.concat(real_ids, ",")
    end
end

mp={}
mp[uid]=tid
result=cjson.encode(mp)
ngx.say(result)





